
package jee.boot.oauth.config;

import jee.boot.common.properties.PermitUrlProperties;
import jee.boot.oauth.config.handler.AuthExceptionEntryPoint;
import jee.boot.oauth.config.token.CustomTokenExtractor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;

/**
 * 资源服务器配置
 */
@Component
@Configuration
@EnableResourceServer
@EnableConfigurationProperties(PermitUrlProperties.class)
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Autowired(required = false)
    private TokenStore redisTokenStore;

    @Autowired
    private OAuth2WebSecurityExpressionHandler expressionHandler;
    @Autowired
    private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
    @Autowired
    private PermitUrlProperties permitUrlProperties;

    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(permitUrlProperties.getHttpUrls());
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(redisTokenStore);
        resources.stateless(true);
        resources.expressionHandler(expressionHandler);
        resources.accessDeniedHandler(oAuth2AccessDeniedHandler);
        resources.tokenExtractor(new CustomTokenExtractor(permitUrlProperties));//对获取token的请求取消token的校验
        resources.authenticationEntryPoint(new AuthExceptionEntryPoint());//认证异常后的信息重写
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers(permitUrlProperties.getOauthUrls()).permitAll()
                .anyRequest().authenticated()
                .and().headers().frameOptions().disable();
    }

}
